package me.luger.core.dao.nutz.callback;

import me.luger.core.commom.util.StringUtil;
import me.luger.core.dao.nutz.entity.NutzTransient;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.impl.sql.callback.EntityCallback;
import org.nutz.dao.pager.ResultSetLooping;
import org.nutz.dao.sql.SqlContext;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by a on 2017/1/11.
 */
public class SingleEntityCallback extends EntityCallback {

    protected String prefix;
    public SingleEntityCallback() {}
    public SingleEntityCallback(String prefix) {
        this.prefix = prefix;
    }

    @Override
    protected Object process(final ResultSet rs, final Entity<?> entity, final SqlContext context)
            throws SQLException {
        if (null != rs && rs.next()){
            final Field[] fields = entity.getMirror().getFields(NutzTransient.class);
            Object obj = entity.getObject(rs, context.getFieldMatcher(), prefix);
            for(Field field : fields){
                try{
                    NutzTransient nutzTransient = field.getAnnotation(NutzTransient.class);
                    String fieldDbName = StringUtil.isBlank(nutzTransient.value()) ? field.getName() : "";
                    if(StringUtil.isNotBlank(prefix)){
                        fieldDbName = prefix + fieldDbName;
                    }
                    Method setMethod = entity.getMirror().getSetter(field);
                    Object rsObj = rs.getObject(fieldDbName);
                    if(null != setMethod && null != rsObj){
                        setMethod.invoke(obj,rsObj);
                    }
                }catch (Exception e){
                    continue;
                }
            }
            return obj;
        }
        return null;
    }
}